package com.example.wangning.mycarofcountry.findcar.brand;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.wangning.mycarofcountry.R;
import com.example.wangning.mycarofcountry.cache.VolleySingleton;
import com.example.wangning.mycarofcountry.tool.BladeView;
import com.example.wangning.mycarofcountry.tool.PinnedHeaderListView;
import com.google.gson.Gson;

import net.sourceforge.pinyin4j.PinyinHelper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dllo on 16/1/14.
 */
public class BrandFragment extends Fragment implements View.OnClickListener {
    private static final String FORMAT = "^[a-z,A-Z].*$";
    private PinnedHeaderListView mListView;
    private BladeView mLetter;
    private FriendsAdapter mAdapter;
    private String[] datas = null;
    //首字母集
    private String[] imgUrls = null;
    //图片数组
    private List<String> mSections;
    //根据首字母存放数据
    private Map<String,List<String>> mMap;
    //首字母位置集
    private List<Integer> mPositions;
    //首字母对应的位置
    private Map<String, Integer> mIndexer;
    private int count = 0;
    private List<String> carName = new ArrayList<>();
    private List<String> imgUrlList = new ArrayList<>();
    private List<CarList> carLists;


    private DrawerLayout mDrawer_layout;  //抽屉式布局
    private LinearLayout mMenu_layout;
    private ListView menu_listview;

    private VolleySingleton queue;
    private ExpandableListView expandableListView;
    private FindCarHotAdapter findCarHotAdapter;

    private Button findCar_hotCar, findCar_hotSUV, findCar_hotMPV, ffffffff;
    private TextView personWeiBoLogin_Tv;
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_findcar_brand,null);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        queue = VolleySingleton.getVolleyIntance();
        mDrawer_layout = (DrawerLayout) view.findViewById(R.id.drawer_layout);

        mDrawer_layout = (DrawerLayout) view.findViewById(R.id.drawer_layout);
        mDrawer_layout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);

        expandableListView = (ExpandableListView) view.findViewById(R.id.findCar_hotcar_expandableListView);
        findCarHotAdapter = new FindCarHotAdapter(view.getContext());
        expandableListView.setAdapter(findCarHotAdapter);

        queue = VolleySingleton.getVolleyIntance();

        findCar_hotCar = (Button) view.findViewById(R.id.findCar_hotCar);
        findCar_hotSUV = (Button) view.findViewById(R.id.findCar_hotSUV);
        findCar_hotMPV = (Button) view.findViewById(R.id.findCar_hotMPV);
        personWeiBoLogin_Tv = (TextView) view.findViewById(R.id.personWeiBoLogin_Tv);

        mListView = (PinnedHeaderListView) view.findViewById(R.id.friends_display);
        mLetter = (BladeView) view.findViewById(R.id.friends_myletterlistview);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);


        if (datas != null && datas.length > 0 && imgUrls != null && imgUrls.length > 0) {
            initData();
        } else {
            getData();
        }

        //去掉二级列表的下拉箭头
        expandableListView.setGroupIndicator(null);


        findCar_hotCar.setOnClickListener(this);
        findCar_hotSUV.setOnClickListener(this);
        findCar_hotMPV.setOnClickListener(this);
        personWeiBoLogin_Tv.setOnClickListener(this);
    }
    private void getData() {
        String url = "http://app.api.autohome.com.cn/autov4.8.5/cars/brandsdealer-pm1-ts0.json";
        queue = VolleySingleton.getVolleyIntance();
        StringRequest request = new StringRequest
                (url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Gson gson = new Gson();
                        Brandsdealer la = gson.fromJson(response, Brandsdealer.class);
                        if (la != null) {
                            CarResult result = la.getResult();

                            if (result != null) {
                                List<Brandlist> brandlists = result.getBrandlist();

                                if (brandlists != null && brandlists.size() > 0) {

                                    for (Brandlist brandlist : brandlists) {
                                        carLists = brandlist.getList();

                                        for (CarList carList : carLists) {
                                            carName.add(carList.getName());
                                            imgUrlList.add(carList.getImgurl());
                                        }
                                    }

                                }
                            }
                        }
                        datas = new String[carName.size()];
                        imgUrls = new String[imgUrlList.size()];
                        for (int i = 0; i < datas.length; i++) {
                            datas[i] = carName.get(i);
                            imgUrls[i] = imgUrlList.get(i);
                        }
                        initData();
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();

                    }
                }) {
            public Map<String, String> getHeaders()
                    throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }
        };
        queue.addRequest(request);
    }

    private void initData() {
        mSections = new ArrayList<String>();
        mMap = new HashMap<String, List<String>>();
        mPositions = new ArrayList<Integer>();
        mIndexer = new HashMap<String, Integer>();
        String firstChar = null;

        for (int i = 0; i < datas.length; i++) {
            String firstName = datas[i].substring(0, 1);
            char name = firstName.charAt(0);
            if ((name + "").matches(FORMAT)) {
                firstChar = name + "";
                if (mSections.contains(firstChar)) {
                    mMap.get(firstChar).add(datas[i]);
                } else {
                    mSections.add(firstChar);
                    List<String> list = new ArrayList<String>();
                    list.add(datas[i]);
                    mMap.put(firstChar, list);
                }
            } else {
                String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(name);
                firstChar = (char) (pinyinArray[0].charAt(0) - 32) + "";
                if ((name + "").equals("长"))
                    firstChar = "C";
                if ((name + "").equals("斯"))
                    firstChar = "S";
                if (firstChar.matches(FORMAT)) {
                    if (mSections.contains(firstChar)) {
                        mMap.get(firstChar).add(datas[i]);
                    } else {
                        mSections.add(firstChar);
                        List<String> list = new ArrayList<String>();
                        list.add(datas[i]);
                        mMap.put(firstChar, list);
                    }
                } else {
                    if (mSections.contains("#")) {
                        mMap.get("#").add(datas[i]);
                    } else {
                        mSections.add("#");
                        List<String> list = new ArrayList<String>();
                        list.add(datas[i]);
                        mMap.put("#", list);
                    }
                }
            }
        }

        Collections.sort(mSections);
        int position = 0;
        for (int i = 0; i < mSections.size(); i++) {
            mIndexer.put(mSections.get(i), position);// 存入map中，key为首字母字符串，value为首字母在listview中位置
            mPositions.add(position);// 首字母在listview中位置，存入list中
            position += mMap.get(mSections.get(i)).size();// 计算下一个首字母在listview的位置
        }
        initView();
    }

    private void initView() {
        // TODO Auto-generated method stub

        mLetter.setOnItemClickListener(new BladeView.OnItemClickListener() {

            @Override
            public void onItemClick(String s) {
                if (mIndexer.get(s) != null) {
                    mListView.setSelection(mIndexer.get(s));
                }
            }
        });
        mAdapter = new FriendsAdapter(getActivity(), datas, imgUrls, mSections, mPositions);
        mListView.setAdapter(mAdapter);
        mListView.setOnScrollListener(mAdapter);
        mListView.setPinnedHeaderView(LayoutInflater.from(getActivity()).inflate(
                R.layout.listview_head, mListView, false));
    }

    @Override
    public void onClick(View v) {
        findCar_hotCar.setBackgroundResource(R.color.white);
        findCar_hotSUV.setBackgroundResource(R.color.white);
        findCar_hotMPV.setBackgroundResource(R.color.white);
        switch (v.getId()) {
            case R.id.findCar_hotCar:
                findCar_hotCar.setBackgroundResource(R.color.blue);
                initDrawData("http://app.api.autohome.com.cn/autov5.0.0/Dealer/hotsaleseries-pm2-st0.json");
                break;
            case R.id.findCar_hotSUV:
                findCar_hotSUV.setBackgroundResource(R.color.blue);
                initDrawData("http://app.api.autohome.com.cn/autov5.0.0/Dealer/hotsaleseries-pm2-st1.json");
                break;
            case R.id.findCar_hotMPV:
                findCar_hotMPV.setBackgroundResource(R.color.blue);
                initDrawData("http://app.api.autohome.com.cn/autov5.0.0/Dealer/hotsaleseries-pm2-st2.json");
                break;
            case R.id.personWeiBoLogin_Tv:
                mDrawer_layout.openDrawer(Gravity.LEFT);
                break;
        }
    }

    private void initDrawData(String url) {
        queue = VolleySingleton.getVolleyIntance();
        StringRequest request = new StringRequest
                (url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Gson gson = new Gson();
                        FindHotCar fi = gson.fromJson(response, FindHotCar.class);
                        if (fi != null) {
                            FindHotCarResult result = fi.getResult();
                            if (result != null) {
                                List<FindHotCarList> findHotCarLists = result.getList();
                                findCarHotAdapter.addData(findHotCarLists);
                                for(int i = 0; i < findCarHotAdapter.getGroupCount(); i++){
                                    expandableListView.expandGroup(i);
                                }
                            }
                        }
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();

                    }
                }) {
            public Map<String, String> getHeaders()
                    throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }
        };
        queue.addRequest(request);
    }

}
